<script>
	const index = require("@/api/index/index.js");
	const personal = require('@/api/personal/index.js')
	export default {
		globalData: {
			code: '',
			ser_url: 'https://wdkj.doit10019.com/',
			// ser_url: 'http://192.168.1.101:3000/',
			userId: '',
			projectId: '',
		},
		async onLaunch() {
			// this.cloud()
			uni.removeStorageSync('tarbar_index')
			console.log('App Launch')
			await this.initData();
		},
		onLaunch: function(e) {},
		onShow: function(e) {
			let paramsa = {
				app_id: this.$https.weixinAppId,
			}

			const params = {};
			// const urlss = window.location.href;
			// const str = decodeURIComponent(window.location.href);
			// const url = str.substring(0, str.length - 2);
			// // const url = 'http://xmswjjh.doit10019.com/h5test?open_id=askdaqweaqewqe&token=1231231231';
			// const paramStr = url.split('?')[1];
			// if (paramStr) {
			// 	const paramArr = paramStr.split('&');
			// 	for (let i = 0; i < paramArr.length; i++) {
			// 		const param = paramArr[i].split('=');
			// 		const key = decodeURIComponent(param[0]);
			// 		// const value = decodeURIComponent(param[1]);
			// 		const value = param.length > 1 ? decodeURIComponent(param[1]) : null;
			// 		        params[key] = value;
			// 		params[key] = value;
			// 	}
			// }
			// 获取当前页面的URL
			const url = new URL(window.location.href);
			
			// 使用URLSearchParams对象获取URL中的参数
			const paramsw = new URLSearchParams(url.search);
			
			// 获取token和open_id参数的值
			const token = paramsw.get('token');
			const open_id = paramsw.get('open_id');
			
			console.log(token); // 输出token参数的值
			console.log(open_id); // 输出open_id参数的值
			// let token = paramsw.token
			// let open_id = paramsw.open_id
			// let open_id = str.substring(0, str.length - 2);
			uni.setStorageSync('openid', open_id)
			uni.setStorageSync('token', token);
			console.log(uni.getStorageSync('token'))
			console.log(uni.getStorageSync('openid'), '+ openid +')
			// if (uni.getStorageSync('token')) {
			// 	this.infoId()
			// }
			if (!uni.getStorageSync('token')) {
				// #ifdef H5
				let params = this.getRequestParams();
				let code = params["code"];
				// #endif

				//let code = e.query.code;
				const openid = uni.getStorageSync('openid');
				let redirect_uri = window.location.href;
				console.log('redirect_uri=', redirect_uri);
				// const scope = 'snsapi_base';
				const scope = 'snsapi_userinfo';
				//不存在code
				if ((!code || code == undefined) && !openid) {
					//获取code （为了方便展示参数 此处缩紧了，真实情况最好不要缩紧）
					document.location.replace(
						`https://open.weixin.qq.com/connect/oauth2/authorize?
					appid=wx82bc471169afa945
					&redirect_uri=${encodeURIComponent(redirect_uri)}
					&response_type=code
					&scope=${scope}
					&state=STATE#wechat_redirect`);
				}

				if ((code && code != undefined) && !openid) {
					// 请求后端接口获取用户的信息
					console.log('result=',result);
					this.infoId(code);

				}
			}
		},
		onHide: function() {
			console.log('App Hide')
			if (uni.getStorageSync("fenx")) {
				this.getPointsByZhuanFa()
			}
		},
		watch: {
			$route() {
				this.directRightUrl()
			}
		},
		methods: {
			infoId(code) {
				uni.request({
					url: this.globalData.ser_url + "manage/wechat.login/official",
					method: 'POST',
					data: {
						code: code,
						applet_id: '',
						project_id: '',
						appid: 'wx82bc471169afa945',
						output: 'json',
					},
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						'Authorization': uni.getStorageSync('token'),

					},
					success: function(res) {
						console.log(res,'[[[111]]]')
						let result = res.data;
						// 保存用户的openid
						if (result.data.user) {
							uni.setStorageSync('userlist', result.data.user)
							uni.setStorageSync('openid', result.data.user.open_id);
						}
					}
				})
			},

			getRequestParams() {
				let url = location.href;
				let requestParams = {};
				if (url.indexOf("?") !== -1) {
					let str = url.substr(url.indexOf("?") + 1); //截取?后面的内容作为字符串
					console.log(str, '?后面的内容');
					let strs = str.split("&"); //将字符串内容以&分隔为一个数组
					console.log(strs, '以&切割的数组');
					for (let i = 0; i < strs.length; i++) {
						requestParams[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
						// 将数组元素中'='左边的内容作为对象的属性名，'='右边的内容作为对象对应属性的属性值
					}
				}
				console.log(requestParams, "处理后的对象");
				return requestParams;
			},
			directRightUrl() {
				let {
					href,
					protocol,
					host,
					pathname,
					search,
					hash
				} = window.location
				search = search || "?"
				let newHref = `${protocol}//${host}${pathname}${search}${hash}`
				console.log("newHref=", newHref);
				if (newHref !== href) {
					window.location.replace(newHref)
				}
			},

			cloud() {
				wx.cloud.callFunction({
					name: 'generateQrCode',
					data: {
						scene: '15651039802', // 传递推荐人ID作为参数
						page: 'pages/index/index', // 小程序码跳转的页面路径
						width: 280 // 小程序码的宽度
					},
					success: res => {
						// 接口调用成功，获取生成的小程序码
						const qrCodeUrl = res.result.qrCodeUrl;
						// 将小程序码展示给用户
						// ...
					},
					fail: err => {
						// 接口调用失败
					}
				});
			},
			// 数据初始化
			async getPointsByZhuanFa() {
				let datas = {
					app_id: this.$https.weixinAppId,
					project_id: getApp().globalData.projectId,
					open_id: uni.getStorageSync("openid"),
				};
				index.getPointsByZhuanFa(datas).then(result => {
					if (result.code == 1) {
						uni.removeStorage({
							key: 'fenx',
							success: function(res) {}
						});
					}
				})
			},
			// 数据初始化
			async initData() {
				// 获取页面设置配置
				const _this = this;
				// 获取学员资料
				let params = {
					app_id: this.$https.weixinAppId,
				}
				// let res = await venues.getProjectIdByAppId(params)
				index.getProjectIdByAppId(params).then(result => {
					// _this.globalData.projectId = result.data.result
					// getApp().globalData.projectId = result.data.result
					getApp().globalData.projectId = result.data.result
					getApp().globalData.sign = result.data.sign;
					let buy_success = result.data.template_ids.buy_success //购买通知id
					let refund_success = result.data.template_ids.refund_success //退款通知id
					let share_success = result.data.template_ids.share_success //分享通知id
					let class_begin = result.data.template_ids.class_begin //分享通知id
					let template_ids = result.data.template_ids //分享通知id
					uni.setStorageSync('buy_success_id', buy_success)
					uni.setStorageSync('refund_success_id', refund_success)
					uni.setStorageSync('share_success_id', share_success)
					uni.setStorageSync('class_begin_id', class_begin)
					uni.setStorageSync('template_ids', template_ids)

					// uni.setStorageSync('projectId',result.data.result)

				})
			},

			onShareAppMessage: function(res) {
				// let rushList = this.data.rushList;
				// let cate_info = rushList && rushList[0].cate_info;
				// var share_title = (cate_info && cate_info.name) || '分类列表';
				var share_title = '五点科技';
				var share_id = 1212;
				var id = 9999;
				var share_path = `page_points/page_points/points_mall?id=${id}&share_id=${share_id}`;

				return {
					title: share_title,
					path: share_path,
					success: function(res) {
						// 转发成功
					},
					fail: function(res) {
						// 转发失败
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uview-ui/index.scss';
	/* 自定义公共css */
	@import '@/common/common.scss';
</style>